package cup.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import cup.core.boot.ctrl.CupController;
import cup.core.excel.util.ExcelUtil;
import cup.core.launch.constant.AppConstant;
import cup.core.mp.support.Condition;
import cup.core.mp.support.Query;
import cup.core.secure.CupUser;
import cup.core.secure.annotation.PreAuth;
import cup.core.secure.utils.AuthUtil;
import cup.core.tenant.annotation.NonDS;
import cup.core.tool.api.R;
import cup.core.tool.constant.RoleConstant;
import cup.core.tool.utils.DateUtil;
import cup.core.tool.utils.Func;
import cup.modules.system.entity.Dept;
import cup.modules.system.entity.Region;
import cup.modules.system.excel.RegionExcel;
import cup.modules.system.excel.RegionImporter;
import cup.modules.system.service.IDeptService;
import cup.modules.system.service.IRegionService;
import cup.modules.system.vo.RegionVO;
import cup.modules.system.wrapper.RegionWrapper;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 行政区划表 控制器
 *
 * @author
 */
@NonDS
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SYSTEM_NAME + "/region")
@Api(value = "行政区划", tags = "行政区划")
public class RegionController extends CupController {

	private final IRegionService regionService;
	private final IDeptService iDeptService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入region")
	public R<RegionVO> detail(Region region) {
		Region detail = regionService.getOne(Condition.getQueryWrapper(region));
		return R.data(RegionWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 行政区划表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入region")
	public R<IPage<Region>> list(Region region, Query query) {
		IPage<Region> pages = regionService.page(Condition.getPage(query), Condition.getQueryWrapper(region));
		return R.data(pages);
	}

	/**
	 * 懒加载列表
	 */
	@GetMapping("/lazy-list")
	@ApiImplicitParams({@ApiImplicitParam(name = "code", value = "区划编号", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "name", value = "区划名称", paramType = "query", dataType = "string")})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "懒加载列表", notes = "传入menu")
	public R<List<RegionVO>> lazyList(String parentCode, @ApiIgnore @RequestParam Map<String, Object> menu) {
		List<RegionVO> list = regionService.lazyList(parentCode, menu);
		return R.data(RegionWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 懒加载列表
	 */
	@GetMapping("/lazy-tree")
	@ApiImplicitParams({@ApiImplicitParam(name = "code", value = "区划编号", paramType = "query", dataType = "string"), @ApiImplicitParam(name = "name", value = "区划名称", paramType = "query", dataType = "string")})
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "懒加载列表", notes = "传入menu")
	public R<List<RegionVO>> lazyTree(String parentCode, @ApiIgnore @RequestParam Map<String, Object> menu) {
		List<RegionVO> list = regionService.lazyTree(parentCode, menu);
		return R.data(RegionWrapper.build().listNodeLazyVO(list));
	}

	/**
	 * 新增 行政区划表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "新增", notes = "传入region")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R save(@Valid @RequestBody Region region) {
		return R.status(regionService.save(region));
	}

	/**
	 * 修改 行政区划表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改", notes = "传入region")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R update(@Valid @RequestBody Region region) {
		return R.status(regionService.updateById(region));
	}

	/**
	 * 新增或修改 行政区划表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "新增或修改", notes = "传入region")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R submit(@Valid @RequestBody Region region) {
		return R.status(regionService.submit(region));
	}


	/**
	 * 删除 行政区划表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "删除", notes = "传入主键")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R remove(@ApiParam(value = "主键", required = true) @RequestParam String id) {
		return R.status(regionService.removeRegion(id));
	}

	/**
	 * 行政区划下拉数据源
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "下拉数据源", notes = "传入tenant")
	public R<List<Region>> select(@RequestParam(required = false, defaultValue = "00") String code,
								  @RequestParam(required = false) Integer f) {
		List<Region> list = regionService.list(Wrappers.<Region>query().lambda().in(Region::getParentCode, Func.toLongList(code)));
		String userRole = AuthUtil.getUserRole();
		if (!CollectionUtils.isEmpty(list)
			&& null != f && f == 1
			&& userRole.contains("district-system")) {
			String deptId = AuthUtil.getDeptId();
			List<Long> longs = Func.toLongList(deptId);
			List<Dept> deptList = iDeptService.listByIds(longs);
			List<Region> myRegionList = regionService.list(new QueryWrapper<Region>()
															   .in("code", deptList.stream().map(Dept::getRegionId).collect(Collectors.toList())));
			List<Region> newList = new ArrayList<>();
			for (Region region : list) {
				for (Region region2 : myRegionList) {
					if (region.getCode().equals(region2.getCode())
						|| region.getCode().equals(region2.getCityCode())
						|| region.getCode().equals(region2.getDistrictCode())) {
						newList.add(region);
					}
				}
			}
			list = newList;
		}
		return R.data(list);
	}

	/**
	 * 导入行政区划数据
	 */
	@PostMapping("import-region")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导入行政区划", notes = "传入excel")
	@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
	public R importRegion(MultipartFile file, Integer isCovered) {
		RegionImporter regionImporter = new RegionImporter(regionService, isCovered == 1);
		ExcelUtil.save(file, regionImporter, RegionExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出行政区划数据
	 */
	@GetMapping("export-region")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "导出行政区划", notes = "传入user")
	public void exportRegion
	(@ApiIgnore @RequestParam Map<String, Object> regionMap, HttpServletResponse response) {
		List<RegionExcel> list = new ArrayList<>();
		List<Region> regions = regionService.list(Condition.getQueryWrapper(regionMap, Region.class));
		if (!CollectionUtils.isEmpty(regions)) {
			for (Region region : regions) {
				RegionExcel regionExcel = new RegionExcel();
				BeanUtils.copyProperties(region, regionExcel);
				list.add(regionExcel);
			}
		}
		ExcelUtil.export(response, "行政区划数据" + DateUtil.time(), "行政区划数据表", list, RegionExcel.class);
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-template")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<RegionExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "行政区划模板", "行政区划表", list, RegionExcel.class);
	}


}
